/**
 * 当前时间戳
 * @param millisecond 是否获取毫秒
 */
export const getTimestamp = (millisecond: boolean = false) => {
    const time = (new Date()).valueOf();
    if (millisecond) {
        return time;
    }
    return Math.ceil(time / 1000);
}

/**
 * 生成随机字符串-已去除难分辨的
 * @param len
 */
export const randomStr = (len: number): string => {
    len = len || 32;
    let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    let maxPos = $chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

/**
 * 数组
 */
export const array = {
    update(list: any[], key: any, data: any, pk: string = 'id') {
        const index = list.findIndex((_) => _[pk] == key);
        if (index >= -1) {
            list.splice(index, 1, { ...list[index], ...data });
        }
    },
    delete(list: any[], key: any, pk: string = 'id') {
        const index = list.findIndex((_) => _[pk] == key);
        if (index >= -1) {
            list.splice(index, 1);
        }
    },
    tree(list: any[], id: string = 'id', pid: string = 'pid', children: string = 'children') {
        let arr: any = JSON.parse(JSON.stringify(list));
        let map: any = {};
        for (let i = 0; i < arr.length; i++) {
            (map[arr[i][id]] as any) = arr[i]
        }
        let newArray: any = [];
        const f = () => {
            for (let i = 0; i < arr.length; i++) {
                let parent = map[arr[i][pid]];
                if (parent) {
                    (parent[children] || (parent[children] = [])).push(arr[i])
                } else {
                    newArray.push(arr[i])
                }
            }
        };
        f();
        return newArray
    },
};
